<template>
  <view class="page">
    <view v-if="$data.info">
      <view class="top">
        <view class="basic">
          <view class="basic_img">
            <image :src="$data.info._picurl" />
          </view>
          <view class="basic_content">
            <view class="basic_content--title">
              {{ $data.info.serviceTitle }}
            </view>
            <view class="basic_content--price text-price">
              {{ $data.info.firstTotalPrice }}
            </view>
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 保障 </view>
          <view class="row_right">
            <view class="flex align-center flex-warp">
              <view
                class="margin-right"
                v-for="(item, index) of $data.info.serviceSnapshot
                  .serviceTagNameArr"
                :key="index"
              >
                <up-icon
                  name="checkmark-circle"
                  color="#111111"
                  labelColor="#111111"
                  :label="item"
                  :size="18"
                  :labelSize="16"
                ></up-icon>
              </view>
            </view>
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 温馨提示 </view>
          <view class="row_right">
            {{ removeHtmlTags($data.info.serviceSnapshot.tips) }}
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 订单总价 </view>
          <view class="row_right text-price">{{ $data.info.totalPrice }}</view>
        </view>
        <view class="row">
          <view class="row_left"> 优惠 </view>
          <view class="row_right text-price">
            -{{ $data.info.couponPrice }}
          </view>
        </view>
        <!-- <view class="row" v-if="$data.info.fast">
          <view class="row_left"> 加急 </view>
          <view class="row_right text-price">
            {{ $data.info.fast }}
          </view>
        </view> -->
        <view class="row">
          <view class="row_left"> 实付金额 </view>
          <view class="row_right">
            <text class="text-price row_right--price">
              {{ $data.info.firstTotalPrice }}
            </text>
          </view>
        </view>
      </view>
      <view class="margin-top padding-lr bg-white">
        <view v-if="false" class="row">
          <view class="row_left"> 服务时间 </view>
          <view class="row_right">
            {{ $data.info._firstStartServicedAt }}
          </view>
        </view>
        <view v-if="false" class="row">
          <view class="row_left"> 服务地址 </view>
          <view class="row_right">
            {{ $data.info.addressSnapshot.locationAddress }}
          </view>
        </view>
        <view v-if="false" class="row">
          <view class="row_left"> 联系人 </view>
          <view class="row_right">
            <text> {{ $data.info.addressSnapshot.name }}</text>
            <text v-if="$data.info.addressSnapshot">
              ({{ $data.info.addressSnapshot.sex == 1 ? "先生" : "女士" }})
            </text>
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 订单编号 </view>
          <view class="row_right">
            <view class="flex justify-between align-center">
              <view>
                {{ $data.info.localNo }}
              </view>
              <view class="copy" @tap="onCopy($data.info.localNo)">复制</view>
            </view>
          </view>
        </view>
        <view class="row">
          <view class="row_left"> 下单时间 </view>
          <view class="row_right">
            {{ $data.info._createdAt }}
          </view>
        </view>
      </view>
      <!-- 底部按钮 -->
      <view class="foot foot_box">
        <block v-if="isDown">
          <view class="btn btn_down">服务已下架</view>
        </block>
        <block v-else>
          <block v-if="$data.info.firstStatus == orderStatus.cancel">
            <view class="btn btn_save btn_pay" @tap="onReset">重新下单</view>
          </block>
          <block v-else>
            <!-- <view class="btn btn_cancel btn_pay" @tap="onCancel">取消订单</view> -->
            <view class="btn btn_save" @tap="onPay">
              <view class="btn_save--title">支付</view>
              <view class="btn_save--time">剩余时间:{{ $data.dayTime }}</view>
            </view>
          </block>
        </block>
      </view>
    </view>
    <PopupLogin />
  </view>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, nextTick, computed } from "vue";
import { onLoad, onShow, onHide, onReady, onUnload } from "@dcloudio/uni-app";
import { cancelOrder, getOrderDetail } from "../../../api/Interface/order";
import errorCode from "../../../utils/http/errorCode";
import dayjs from "dayjs";
import "dayjs/locale/zh-cn";
import duration from "dayjs/plugin/duration";
import { usePayment } from "../../../hooks/usePay";
import BasicConfig from "../../../utils/config";
import {
  hotelOrderAfterSaleStatus,
  orderSourceType,
  orderStatus,
  orderStatusConfig,
  searchOrderStatus,
} from "../../../enums/order";
import { jumpPage } from "../../../utils/route/route";
import { useImgSrc } from "../../../hooks/useImg";
import { removeHtmlTags } from "../../../utils/utils";
dayjs.extend(duration);
const Instance = getCurrentInstance();
const $vm = Instance?.appContext.config.globalProperties;
const $data = reactive({
  localNo: "",
  orderServiceId: "",
  info: null,
  timer: null,
  remainingTime: 0,
  dayTime: "",
});
const onPay = () => {
  // uni.showModal({
  //   content: "确定支付?",
  //   confirmColor: BasicConfig.MainColor,
  //   success: (success) => {
  //     if (success.confirm) {
  //       usePayment(
  //         { localNo: $data.localNo, type: orderSourceType.daily },
  //         "wechat"
  //       ).then((res) => {
  //         if (res.code === errorCode.success) {
  //           BasicConfig.toast(res.msg);
  //           setTimeout(() => {
  //             init();
  //           }, 1000);
  //         } else {
  //           BasicConfig.toast("支付失败,请联系管理员!");
  //         }
  //       });
  //     }
  //   },
  // });
  BasicConfig.loadToast("调起支付...");
  try {
    tt.continueToPay({
      outOrderNo: $data.localNo,
      success(res) {
        console.log("continueToPay res", res);
        setTimeout(() => {
          // init();
					jumpPage({
					  to: "/package-service/pages/order/details/awaitReservation",
					  mode: "redirectTo",
					  query: {
					    localNo: $data.localNo,
					    orderServiceId: $data.orderServiceId,
					  },
					});
        }, 10);
      },
      fail(err) {
        console.log("continueToPay err", err);
        if (err.errMsg.includes("payment is cancelled")) {
        } else {
          uni.showModal({
            content: "支付失败，请联系管理员！",
            showCancel: false,
            confirmText: "知道了",
            cancelColor: BasicConfig.MainColor,
          });
        }
      },
      complete() {
        uni.hideLoading();
      },
    });
  } catch (e) {
    uni.hideLoading();
  }
};
const onCancel = () => {
  jumpPage({
    to: "/package-service/pages/order/details/cancel",
    query: {
      localNo: $data.localNo,
    },
  });
  // uni.showModal({
  //   content: "确定取消订单?",
  //   confirmColor: BasicConfig.MainColor,
  //   success: (success) => {
  //     if (success.confirm) {
  //       cancelOrder({ localNo: $data.localNo }).then((res) => {
  //         BasicConfig.toast(res.msg);
  //         if (res.code === errorCode.success) {
  //           setTimeout(() => {
  //             init();
  //           }, 1000);
  //         }
  //       });
  //     }
  //   },
  // });
};
const onReset = () => {
  if (isDown.value) {
    BasicConfig.toast("服务已下架");
    return;
  }
  jumpPage({
    to: "/package-service/pages/index",
    mode: "reLaunch",
    query: {
      id: $data.info.serviceSnapshot.domesticServiceId,
    },
  });
};
const onCopy = (text) => {
  uni.setClipboardData({
    data: text.toString(),
    success: (result) => {
      BasicConfig.toast("复制成功");
    },
    fail: (error) => {
      console.log("复制失败", error);
      BasicConfig.toast("复制失败!");
    },
  });
};
const init = () => {
  clearCountdown();
  getOrderDetail({
    localNo: $data.localNo,
    orderServiceId: $data.orderServiceId,
  }).then((res) => {
    if (res.code === errorCode.success) {
      $data.info = res.data;
      if ($data.info) {
        setTitle();
        $data.info._picurl = useImgSrc($data.info.picurl);
        $data.info.addressSnapshot = $data.info.addressSnapshot ?? {};
        onDetail();
        const { firstStartServicedAt, createdAt, countDown } = res.data;
        $data.info._firstStartServicedAt = firstStartServicedAt
          ? dayjs(firstStartServicedAt)
              .locale("zh-cn")
              .format("YYYY-MM-DD dddd HH:mm")
          : "";
        $data.info._createdAt = createdAt
          ? dayjs(createdAt).locale("zh-cn").format("YYYY-MM-DD dddd HH:mm")
          : "";
        countdown();
      }
    }
  });
};
// 根据不同状态跳转不同页面
const onDetail = () => {
  console.log("onDetail 页面转发", $data.info);
  const { status, orderServiceId, localNo, firstAfterSaleStatus } = $data.info;
  // 部分退款
  if (
    firstAfterSaleStatus != hotelOrderAfterSaleStatus.normal &&
    firstAfterSaleStatus != hotelOrderAfterSaleStatus.allEnd
  ) {
    jumpPage({
      to: "/package-service/pages/order/afterSales/apply",
      mode: "redirectTo",
      query: {
        localNo,
        orderServiceId,
      },
    });
    return;
  }
  // 全部退款
  else if (firstAfterSaleStatus == hotelOrderAfterSaleStatus.allEnd) {
    jumpPage({
      to: "/package-service/pages/order/order",
      mode: "redirectTo",
      query: {
        status: searchOrderStatus.afterSales,
      },
    });
    return;
  } else if (status == orderStatus.awaitPay) {
  } else if (status == orderStatus.finding) {
    jumpPage({
      to: "/package-service/pages/order/details/finding",
      mode: "redirectTo",
      query: {
        localNo,
        orderServiceId,
      },
    });
    return;
  } else if (status == orderStatus.awaitService) {
    jumpPage({
      to: "/package-service/pages/order/details/awaitService",
      mode: "redirectTo",
      query: {
        localNo,
        orderServiceId,
      },
    });
    return;
  } else if (status == orderStatus.awaitConfirm) {
    jumpPage({
      to: "/package-service/pages/order/details/awaitConfirm",
      mode: "redirectTo",
      query: {
        localNo,
        orderServiceId,
      },
    });
    return;
  } else if (status == orderStatus.awaitComment) {
    jumpPage({
      to: "/package-service/pages/order/details/final",
      mode: "redirectTo",
      query: {
        localNo,
        orderServiceId,
      },
    });
    return;
  } else if (status == orderStatus.final) {
    jumpPage({
      to: "/package-service/pages/order/details/final",
      mode: "redirectTo",
      query: {
        localNo,
        orderServiceId,
      },
    });
    return;
  } else if (status == orderStatus.serving) {
    jumpPage({
      to: "/package-service/pages/order/details/serving",
      mode: "redirectTo",
      query: {
        localNo,
        orderServiceId,
      },
    });
    return;
  } else if (status == orderStatus.awaitReservation) {
    jumpPage({
      to: "/package-service/pages/order/details/awaitReservation",
      mode: "redirectTo",
      query: {
        localNo,
        orderServiceId,
      },
    });
  }
};
const countdown = () => {
  const { countDown = 0 } = $data.info;
  $data.remainingTime = Number(countDown);
  if ($data.remainingTime && $data.remainingTime > 0) {
    $data.timer = setInterval(() => {
      if ($data.remainingTime > 0) {
        $data.remainingTime--;
        $data.dayTime = dayjs
          .duration($data.remainingTime, "seconds")
          .format("HH:mm:ss");
      } else {
        init();
        clearCountdown();
      }
    }, 1000);
  } else {
    clearCountdown();
  }
};
const clearCountdown = () => {
  $data.remainingTime = 0;
  $data.dayTime = "";
  clearInterval($data.timer);
  $data.timer = null;
};
const setTitle = () => {
  console.log(
    "orderStatusConfig[$data.info.firstStatus]",
    orderStatusConfig[$data.info.firstStatus],
    orderStatusConfig,
    $data.info.firstStatus
  );
  uni.setNavigationBarTitle({
    title: orderStatusConfig[$data.info.firstStatus]?.label ?? "",
  });
};
/** 是否下架 domesticServiceStatus 0.已下架 1.已上架 */
const isDown = computed(() => {
  const { domesticServiceStatus } = $data.info;
  return domesticServiceStatus == 0;
});
onLoad((options) => {
  $data.localNo = options.localNo;
  $data.orderServiceId = options.orderServiceId;
});
onShow(() => {
  setTimeout(() => {
    init();
  }, 1000);
});
onUnload(() => {
  console.log("onUnload~~~~~~~~~~~");
  clearCountdown();
});
onReady(() => {});
</script>

<style lang="scss" scoped>
@import "../../static/style/order/detail/common.scss";
</style>
